<template>
  <div class="bgc-default">
    <!-- 编辑查看 -->
    <template v-if="activeName == '1'">
      <div class="top-nav">
        <template v-for="(item, index) of topNavBar">
          <div :key="index" class="nav-item" :class="{'nav-active' : topNavBaroIndex === index}"
            @click="goTarget('#' + item.target, index)">{{item.name}}</div>
        </template>
      </div>
      <div class="circle-x-tab pad-l-20 pad-r-20 mar-t-20">
        <!-- 基本信息 -->
        <goods-info id="base-info" class="scroll-item" :dict="dict" ref="goodsInfo"></goods-info>
        <!-- 供应链/库存 -->
        <goods-supplier id="in-stock" :supplierGoodsId="supplierGoodsId" class="scroll-item" :dict="dict"
          ref="goodsSupplier"></goods-supplier>
        <!-- 价格设置 -->
        <goods-price id="price-set" class="scroll-item" :supplierGoodsId="supplierGoodsId" :dict="dict"
          ref="goodsPrice"></goods-price>
        <!-- 参数设置 -->
        <goods-parameter id="params-set" class="scroll-item" ref="goodsParameter"></goods-parameter>
        <!-- 商品详情 -->
        <goods-detail id="goods-detail" class="scroll-item mar-r-30" ref="goodsDetail"></goods-detail>
        <!-- 其他设置 -->
        <goods-other id="other-set" class="scroll-item" :dict="dict" ref="goodsOther"></goods-other>
        <!-- 商品其它 -->
        <el-form :model="goodsInfo" label-width="130px" ref="form" style="margin-top: -12px;" v-if="goodsInfo.reject">
          <el-form-item label="未通过原因" class="one-label">
            <el-form-item label="" label-width="170px">
              {{goodsInfo.reject}}
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div class="bottom-bar">
        <el-button @click="$router.go(-1)">返回</el-button>
        <el-button class="mar-l-30" type="primary" @click="saveGoodsInfo">保存</el-button>
      </div>
    </template>

    <!-- 详情查看 -->
    <template v-if="activeName == '2'">
      <!-- 商品信息 -->
      <goods-info-see :dict="dict" class="detail-content" ref="goodsInfoSee"></goods-info-see>
      <!-- 商品价格库存 -->
      <goods-price-see :dict="dict" class="detail-content" ref="goodsPriceSee"></goods-price-see>
      <el-form class="text-c" style="margin-top: -12px;">
        <el-form-item>
          <div class="mar-t-10 mar-b-10">
            <el-button type="primary" @click="updateWithdrawAuditType">撤回审核</el-button>
            <el-button @click="handleOut">返回</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </div>
</template>

<script>
  import goodsInfo from './components/goods-info'
  import goodsPrice from './components/goods-price'
  import goodsInfoSee from './components/goods-info-see'
  import goodsPriceSee from './components/goods-price-see'
  import goodsParameter from './components/goods-parameter'
  import goodsDetail from './components/goods-detail'
  import goodsSupplier from './components/goods-supplier'
  import goodsOther from './components/goods-other'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    getSupplierGoodsDetail,
    updateWithdrawAuditType
  } from '@/api/goods/supplierGoods'
  import {
    saveGoods
  } from '@/api/goods/supplierGoods'

  export default {
    components: {
      goodsInfo,
      goodsPrice,
      goodsInfoSee,
      goodsPriceSee,
      goodsParameter,
      goodsDetail,
      goodsSupplier,
      goodsOther
    },
    data() {
      return {
        activeName: '1',
        auditType: '0',
        enterpriseId: this.getEnterpriseId(),
        dict: {},
        supplierGoodsId: '',
        templateId: null,
        listLoading: false,
        goodsInfo: {},
        topNavBar: [{
          name: '基本信息',
          target: 'base-info'
        },
        {
          name: '供应链/库存',
          target: 'in-stock'
        },
        {
          name: '价格设置',
          target: 'price-set'
        },
        {
          name: '参数设置',
          target: 'params-set'
        },
        {
          name: '商品详情',
          target: 'goods-detail'
        },
        {
          name: '其他设置',
          target: 'other-set'
        }
        ],
        topNavBaroIndex: 0
      }
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      const supplierGoodsId = queryParams.supplierGoodsId
      this.activeName = queryParams.activeName
      if (queryParams && queryParams.auditType) {
        this.auditType = queryParams.auditType
      }
      if (supplierGoodsId) {
        this.supplierGoodsId = supplierGoodsId
      }
    },
    beforeDestroy() {
      window.removeEventListener('mousewheel', this.getDomTop)
    },
    mounted() {
      this.$nextTick(function() {
        const queryParams = this.getCurrentPage().query
        if (queryParams.active) {
          this.goTarget(`#${this.topNavBar[queryParams.active]['target']}`, queryParams.active)
        }
        for (let i = 0; i < this.topNavBar.length; i++) {
          const dom = document.getElementById(`${this.topNavBar[i]['target']}`)
          this.$set(this.topNavBar[i], 'top', dom.offsetTop)
          this.$set(this.topNavBar[i], 'h', dom.clientHeight)
        }
      })
      window.addEventListener('mousewheel', this.getDomTop)
      if (this.supplierGoodsId) {
        this.initGoodsInfo()
      } else {
        this.$refs.goodsDetail.detailsBoolean = true
      }
      this.initDict()
      // 监听
      this.busMonitor()
    },
    methods: {
      getDomTop() {
        const that = this
        const scroll = document.documentElement.scrollTop || document.body.scrollTop
        const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
        for (let i = 0; i < that.topNavBar.length; i++) {
          const dom_id = `${that.topNavBar[i]['target']}`.trim()
          const dom_top = document.getElementById(dom_id).getBoundingClientRect().top
          if (dom_top < 250 && dom_top > 0) {
            that.topNavBaroIndex = i
          }
          if (scroll + windowHeight === scrollHeight) {
            that.topNavBaroIndex = that.topNavBar.length - 1
          }
        }
      },
      goTarget(id, index) {
        document.querySelector(id).scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
        this.topNavBaroIndex = index
      },
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      busMonitor() {
        // 文本表单值设置
        const that = this
        this.$bus.$on('ComponentTemplate.bindTemplateId', function(data) {
          console.log('ComponentTemplate.bindTemplateId')
          if (data.componentType === 'componentAnchorDetail') {
            // Cannot read property 'componentType' of null 异常 先做undefined校验
            that.anchorTemplateId = data.templateId
          } else {
            that.templateId = data.templateId
          }
          if (data.needSaveGoods) {
            that.saveData()
          }
        })
      },
      initGoodsInfo() {
        getSupplierGoodsDetail(this.supplierGoodsId).then((response) => {
          this.goodsInfo = response.data
          this.$bus.$emit('goods.edit.data', response.data)
        })
      },
      // 撤回审核
      updateWithdrawAuditType(row) {
        this.$confirm('商品正在等待企业审核，确定要撤回审核？', '提示', {
          confirmButtonText: '撤回审核',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateWithdrawAuditType(this.supplierGoodsId).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '成功'
            })
            this.handleOut()
          })
        })
      },
      // 退出
      handleOut() {
        this.$router.push({
          path: '/goods/supplier-goods/index',
          query: {
            auditType: this.auditType
          }
        })
      },
      // 商品保存事件
      saveGoodsInfo() {
        let checkRet = true
        // 基础信息校验
        checkRet = this.$refs.goodsInfo.checkForm()
        if (!checkRet) {
          return
        }
        // 价格组件校验
        checkRet = this.$refs.goodsPrice.checkForm()
        if (!checkRet) {
          return
        }
        // 保存模板
        this.$refs.goodsDetail.saveTemplate()
      },
      saveData() {
        const title = this.$refs.goodsInfo.form.title
        const goodsArticleNo = this.$refs.goodsInfo.form.goodsArticleNo
        const shareCopy = this.$refs.goodsInfo.form.shareCopy
        const unit = this.$refs.goodsInfo.form.unit
        // 图片集合
        const goodsImages = this.$refs.goodsInfo.form.goodsImages
        // 商品分类Id
        const goodscategoryIds = this.$refs.goodsInfo.form.goodscategoryIds
        // 跨境类型
        const crossBorderType = this.$refs.goodsInfo.form.crossBorderType
        const wholesaleGoodscategoryIds = this.$refs.goodsInfo.form.wholesaleGoodscategoryIds
        const shareImageUrl = this.$refs.goodsInfo.form.shareImageUrl
        const posterImageUrl = this.$refs.goodsInfo.form.posterImageUrl
        const picUrl = this.$refs.goodsInfo.form.picUrl
        const posterTitle = this.$refs.goodsInfo.form.posterTitle
        const sellPoint = this.$refs.goodsInfo.form.sellPoint
        const brandId = this.$refs.goodsInfo.form.brandId
        const goodsBarCode = this.$refs.goodsInfo.form.goodsBarCode
        const oneCategoryId = goodscategoryIds[0]
        const twoCategoryId = goodscategoryIds[1]
        const threeCategoryId = goodscategoryIds[2]
        const wholesaleOneCategoryId = wholesaleGoodscategoryIds[0]
        const wholesaleTwoCategoryId = wholesaleGoodscategoryIds[1]
        const wholesaleThreeCategoryId = wholesaleGoodscategoryIds[2]
        const skuFlag = this.$refs.goodsSupplier.form.skuFlag
        const stock = this.$refs.goodsSupplier.form.stock

        const supplyPrice = this.$refs.goodsPrice.form.supplyPrice
        const supplierPostFee = this.$refs.goodsPrice.form.supplierPostFee
        const supplierTaxFlag = this.$refs.goodsPrice.form.supplierTaxFlag
        const taxItemsId = this.$refs.goodsPrice.form.taxItemsId
        const externalCode = this.$refs.goodsPrice.form.externalCode
        const enterpriseId = this.enterpriseId
        const templateId = this.templateId

        const qualityData = this.$refs.goodsPrice.form.qualityData
        const qualityTable = this.$refs.goodsPrice.form.qualityTable
        const scribingPrice = this.$refs.goodsPrice.form.scribingPrice

        const goodsParameters = this.$refs.goodsParameter.form.goodsParameters

        const weight = this.$refs.goodsOther.form.weight
        const size = this.$refs.goodsOther.form.size
        var prov = this.$refs.goodsOther.form.prov
        var city = this.$refs.goodsOther.form.city

        const table = []
        if (qualityData.length === 1) {
          const skuPropId = qualityData[0].skuPropId
          const skuPropName = qualityData[0].skuPropName
          const singleTable = this.$refs.goodsPrice.form.singleTable
          for (let i = 0; i < singleTable.length; i++) {
            const imageUrl = this.$utils.isExist(singleTable[i].imageUrl) ? singleTable[i].imageUrl : ''
            const price = this.$utils.isExist(singleTable[i].price) ? singleTable[i].price : ''
            const skuSupplyPrice = this.$utils.isExist(singleTable[i].supplyPrice) ? singleTable[i].supplyPrice : ''
            const skuScribingPrice = this.$utils.isExist(singleTable[i].scribingPrice) ? singleTable[i].scribingPrice
              : ''
            const goodsBarCode = this.$utils.isExist(singleTable[i].goodsBarCode) ? singleTable[i].goodsBarCode : ''
            const externalCode = this.$utils.isExist(singleTable[i].externalCode) ? singleTable[i].externalCode : ''
            const stock = this.$utils.isExist(singleTable[i].stock) ? singleTable[i].stock : ''

            const skuPropValueId = singleTable[i].skuPropValueId
            const skuPropValue = singleTable[i].skuPropValue

            const projectGoodsSkuDTO = {}
            projectGoodsSkuDTO.skuId = singleTable[i].skuId || ''
            projectGoodsSkuDTO.imageUrl = imageUrl
            projectGoodsSkuDTO.price = price
            projectGoodsSkuDTO.supplyPrice = skuSupplyPrice
            projectGoodsSkuDTO.scribingPrice = skuScribingPrice
            projectGoodsSkuDTO.goodsBarCode = goodsBarCode
            projectGoodsSkuDTO.externalCode = externalCode
            projectGoodsSkuDTO.stock = stock
            const skuPropValueList = []
            const propValue = {
              skuPropId: skuPropId,
              skuPropName: skuPropName,
              skuPropValueId: skuPropValueId,
              skuPropValue: skuPropValue
            }
            skuPropValueList.push(propValue)
            projectGoodsSkuDTO.skuPropValueList = skuPropValueList
            table.push(projectGoodsSkuDTO)
          }
        } else {
          for (let i = 0; i < qualityTable.length; i++) {
            const item = qualityTable[i]
            const projectGoodsSkuDTO = {}
            projectGoodsSkuDTO.skuId = item.skuId || ''
            projectGoodsSkuDTO.imageUrl = this.$utils.isExist(item['imageUrl']) ? item['imageUrl'] : ''
            projectGoodsSkuDTO.price = this.$utils.isExist(item['price']) ? item['price'] : ''
            projectGoodsSkuDTO.supplyPrice = this.$utils.isExist(item['supplyPrice']) ? item['supplyPrice'] : ''
            projectGoodsSkuDTO.scribingPrice = this.$utils.isExist(item['scribingPrice']) ? item['scribingPrice'] : ''
            projectGoodsSkuDTO.stock = this.$utils.isExist(item['stock']) ? item['stock'] : ''
            projectGoodsSkuDTO.goodsBarCode = this.$utils.isExist(item['goodsBarCode']) ? item['goodsBarCode'] : ''
            projectGoodsSkuDTO.externalCode = this.$utils.isExist(item['externalCode']) ? item['externalCode'] : ''
            const skuPropValueList = []
            for (const key in item) {
              if (this.$utils.isExist(item[key].skuPropId)) {
                const skuPropId = item[key].skuPropId
                const skuPropName = item[key].skuPropName
                const skuPropValue = item[key].skuPropValue
                const skuPropValueId = item[key].skuPropValueId
                const projectGoodsSkuPropValueDTO = {
                  skuPropId: skuPropId,
                  skuPropName: skuPropName,
                  skuPropValue: skuPropValue,
                  skuPropValueId: skuPropValueId
                }
                skuPropValueList.push(projectGoodsSkuPropValueDTO)
              }
            }
            projectGoodsSkuDTO.skuPropValueList = skuPropValueList
            table.push(projectGoodsSkuDTO)
          }
        }

        // 海关商品编码id
        const customsGoodsCodeId = this.$refs.goodsInfo.form.customsGoodsCodeId
        // 商品产地-国家
        const countryId = this.$refs.goodsOther.form.countryId
        const countryName = this.$refs.goodsOther.form.countryName
        // 中国的id
        if (countryId !== '1447771317507129386') {
          // 不等于中国，省市清空
          prov = ''
          city = ''
        }
        const data = {
          enterpriseId: enterpriseId,
          supplierId: this.getSupplierId(),
          title: title,
          goodsArticleNo: goodsArticleNo,
          shareCopy: shareCopy,
          unit: unit,
          shareImageUrl: shareImageUrl,
          posterImageUrl: posterImageUrl,
          picUrl: picUrl,
          posterTitle: posterTitle,
          sellPoint: sellPoint,
          goodsImages: goodsImages,
          brandId: brandId,
          oneCategoryId: oneCategoryId,
          twoCategoryId: twoCategoryId,
          threeCategoryId: threeCategoryId,
          wholesaleOneCategoryId: wholesaleOneCategoryId,
          wholesaleTwoCategoryId: wholesaleTwoCategoryId,
          wholesaleThreeCategoryId: wholesaleThreeCategoryId,
          skuFlag: skuFlag,
          supplyPrice: supplyPrice,
          scribingPrice: scribingPrice,
          stock: stock,
          supplierPostFee: supplierPostFee,
          taxItemsId: taxItemsId,
          supplierTaxFlag: supplierTaxFlag,
          goodsBarCode: goodsBarCode,
          externalCode: externalCode,
          supplierGoodsId: this.supplierGoodsId,
          goodsParameters: goodsParameters,
          detailTemplateId: templateId,
          qualityData: qualityData,
          qualityTable: table,
          weight: weight,
          size: size,
          prov: prov,
          city: city,
          crossBorderType: crossBorderType,
          customsGoodsCodeId: customsGoodsCodeId,
          countryId: countryId,
          countryName: countryName
        }
        this.isSubmit = true
        if (!this.isSubmit) {
          return
        }
        this.listLoading = true

        this.loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        saveGoods(data).then((response) => {
          this.listLoading = false
          this.loading.close()
          if (response.isError) {
            return
          }
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.$bus.$off('ComponentTemplate.bindTemplateId')
          this.handleOut()
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .circle-x-tab {
    padding-bottom: 70px;

    /deep/.el-checkbox__label {
      font-size: 16px;
    }

    /deep/.el-radio__label {
      font-size: 14px;
    }

    /deep/.el-checkbox__inner {
      width: 14px;
      height: 14px;
    }

    /deep/.el-checkbox__inner {
      width: 18px;
      height: 18px;
    }

    /deep/.form-diy .el-form-item {
      background: none;
    }

    /deep/.form-diy .el-form-item.none-mar-b {
      margin-bottom: 0 !important;
    }

    /deep/.form-diy .el-color-picker--medium .el-color-picker__trigger {
      width: 100px;
    }

    /deep/.form-diy .el-color-picker__empty,
    /deep/.form-diy .el-color-picker__icon {
      left: 80%;
    }

    /deep/.form-diy .el-form-item__label {
      font-size: 14px !important;
      font-weight: normal !important;
    }

    /deep/.form-diy .el-upload--picture-card {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/.el-form-item {
      background: white;
    }

    /deep/.el-form-item .el-form-item {
      margin-bottom: 22px;
    }

    /deep/.one-label>.el-form-item__label {
      text-align: center;
      font-size: 18px;
      padding-top: 22px;
    }

    /deep/.one-label>.el-form-item__content {
      padding: 20px 50px 20px 0;
      border-left: #F7F8FA 10px solid;

      .el-form-item__label {
        font-size: 14px;
      }
    }

    /deep/.el-form-item__content {
      font-size: 14px;

      .el-form-item__label {
        font-size: 18px;
        font-weight: normal;
      }
    }
  }

  .top-nav {
    position: sticky;
    top: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: space-around;
    z-index: 999;
    box-shadow: 0 2px 6px #eee;

    .nav-item {
      cursor: pointer;
    }

    .nav-active {
      position: relative;
      color: #409eff;

      &::after {
        content: '';
        position: absolute;
        bottom: -20px;
        left: -15px;
        width: calc(100% + 30px);
        height: 2px;
        background-color: #409eff;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    z-index: 999;
    box-shadow: 5px 1px 5px #cccccc;

    .el-button {
      width: 100px;
      height: 40px;
      line-height: 40px;
      padding: 0;
    }

    .el-button+.el-button {
      margin-left: 30px;
    }
  }

  .el-form-item__content {
    .el-button {
      padding: 0;
      height: 34px;
      width: 139px;
    }
  }

  .span-bar {
    padding: 0 50px;
  }

  .remove-btn {
    padding: 7px 6px !important;
  }

  .long-input {
    width: 80%;
  }

  .long-input-2 {
    width: 55%;
    margin-right: 5%;
  }

  .long-input-3 {
    width: 55%;
  }

  .short-input {
    width: 20%;
  }

  .short-input-2 {
    width: 25%;
  }

  .default-input {
    width: 50%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .picture {
    width: 130px;
    height: 130px;
    display: block;
  }

  .pic-bar {
    position: relative;

    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .pic-add {
    background: #fff;
    border: #d3d3d3 1px dashed;
    border-radius: 5px;
    padding: 0 45px;
  }

  .bottom-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
</style>
